<?php
// 本类由系统自动生成，仅供测试用途
namespace Api\Controller;

use Think\Controller;
use Org\Util\Token;

class PaymentController extends PublicController
{


    /**
     * 会员立即购买产品
     * @author tiedong
     * @date 2018-01-19
     */
    public function buy_now()
    {
        $uid = intval($this->get("id"));
        if (!$uid) {
            echo json_encode(array('status' => 0, 'err' => '请登录.'));
            exit();
        }
        $product = M("product");
        $price = isset($_GET['price']) ? $_GET['price'] : 0;//总价格
        $b_id = isset($_GET['b_id']) ? intval($_GET['b_id']) : 0;//心意卡id
        $bi_id = isset($_GET['brand_image_id']) ? intval($_GET['brand_image_id']) : 0;//卡面图片
        $num = isset($_GET['num']) ? intval($_GET['num']) : 0;//总数量
        if (!intval($num) && !intval($price)) {
            $this->json_error("参数错误");
            exit();
        }
        $proArr = array();
        $pids_arr = isset($_GET['pids']) ? $_GET['pids'] : 0;//商品id
        //$pids_arr = "278_4,279_4";
        $pids = explode(",", $pids_arr);
        foreach ($pids as $value) {
            $pid = explode("_", $value);
            //检查商品是否已经下架或者不存在！
            $check = $this->check_cart(intval($pid[0]));
            if ($check['status'] == 0) {
                $this->json_error($check['err']);
                exit;
            }
            //检查商品的库存
            $check = $this->check_num(intval($pid[0]), intval($pid[1]));
            if ($check['status'] == 0) {
                $this->json_error($check['err']);
                exit;
            }
            $pro_info = $product->where('id=' . intval($pid[0]))->field('name,price')->find();
            $pro_info['num'] = $pid[1];
            array_push($proArr, $pro_info);
        }
        $brand = M("brand")->where("id=" . $b_id)->find();
        $brand_photo = __DATAURL__ . "UploadFiles/" . M("brand_image")->where("id=" . $bi_id)->getField("brand_photo");

        //获取积分
        $jifen = M("user")->where('id=' . $uid)->getField("jifen");
        $returnArr = array(
            'brand_id'       => $b_id,
            'brand_image_id' => $bi_id,
            'brand_name'     => $brand['name'],
            'brand_photo'    => $brand_photo,
            'price'          => $price,
            'pids'           => $pids_arr,
            'jifen'          => $jifen,
            'jifen_price'    => $jifen / 100,
            'token'          => Token::issueCrumb($this->get("id")),
            'product'        => $proArr,
            'can_jifen'      => $brand['type'],
        );
        $this->json_result($returnArr);
        //单件商品结算
        //地址管理
        /*$address=M("address");
        $city=M("china_city");
        $add=$address->where('uid='.intval($uid))->select();
        $citys=$city->where('tid=0')->field('id,name')->select();
        $shopping=M('shopping_char');
        $product=M("product");
        //运费
        $post = M('post');

        //立即购买数量
        $num=intval($_REQUEST['num']);
        if (!$num) {
            $num=1;
        }

        //购物车id
        $cart_id = intval($_REQUEST['cart_id']);
        //检测购物车是否有对应数据
        $check_cart = $shopping->where('id='.intval($cart_id).' AND num>='.intval($num))->getField('pid');
        if (!$check_cart) {
            echo json_encode(array('status'=>0,'err'=>'购物车信息错误.'));
            exit();
        }
        //判断基本库存
        $pro_num = $product->where('id='.intval($check_cart))->getField('num');
        if ($num>intval($pro_num)) {
            echo json_encode(array('status'=>0,'err'=>'库存不足.'));
            exit();
        }

        $qz=C('DB_PREFIX');//前缀

        $pro=$shopping->where(''.$qz.'shopping_char.uid='.intval($uid).' and '.$qz.'shopping_char.id='.intval($cart_id))
                        ->join('LEFT JOIN __PRODUCT__ ON __PRODUCT__.id=__SHOPPING_CHAR__.pid')
                          ->join('LEFT JOIN __SHANGCHANG__ ON __SHANGCHANG__.id=__SHOPPING_CHAR__.shop_id')
            ->field(''.$qz.'product.num as pnum,'.$qz.'shopping_char.id,'.$qz.'shopping_char.pid,'.$qz.'shangchang.name as sname,'.$qz.'product.name,'.$qz.'product.shop_id,'.$qz.'product.photo_x,'.$qz.'product.price_yh,'.$qz.'shopping_char.num,'.$qz.'shopping_char.buff,'.$qz.'shopping_char.price,'.$qz.'shangchang.alipay,'.$qz.'shangchang.alipay_pid,'.$qz.'shangchang.alipay_key')
            ->find();
        //获取运费
        $yunfei = $post->where('pid='.intval($pro['shop_id']))->find();

        if($pro['buff']!=''){
            $pro['zprice']=$pro['price']*$num;
        }else{
            $pro['price']=$pro['price_yh'];
            $pro['zprice']=$pro['price']*$num;
        }

        //如果需要运费
        if ($yunfei) {
            if ($yunfei['price_max']>0 && $yunfei['price_max']<=$pro['zprice']) {
                $yunfei['price']=0;
            }
        }

        $buff_text='';
        if($pro['buff']){
            //获取属性名称
            $buff = explode(',',$pro['buff']);
            if(is_array($buff)){
                foreach($buff as $keys => $val){
                    $ggid=M("guige")->where('id='.intval($val))->getField('name');
                    //$buff_text .= select('name','aaa_cpy_category','id='.$val['id']).':'.select('name','aaa_cpy_category','id='.$val['val']).' ';
                    $buff_text .=' '.$ggid.' ';
                }
            }
        }
        $pro['buff']=$buff_text;
        $pro['photo_x']='http://'.$_SERVER['SERVER_NAME'].__UPLOAD__.'/'.$pro['photo_x'];

        echo json_encode(array('status'=>1,'citys'=>$citys,'yun'=>$yunfei,'adds'=>$add,'pro'=>$pro,'num'=>$num,'buff'=>$buff_text));*/
        exit();
        //$this->assign('citys',$citys);
    }

    /**
     * 会员下单立即购买
     * @throws \Exception
     */
    public function pay_now()
    {
        if (!Token::verifyCrumb($this->get("id"), $_POST['token'])) {
            $this->json_error("表单已经提交，请勿重复提交");
        }
        $product = M("product");
        //运费
        //$post = M('post');
        $order = M("order");
        $order_pro = M("order_product");

        $uid = intval($this->get("id"));
        if (!$uid) {
            echo json_encode(array('status' => 0, 'err' => '登录状态异常.'));
            exit();
        }
        //返回一个公共的订单号
        $order_sn = $this->build_order_no();
        //获取积分金额
        $ji_price = !empty($_POST['ji_price']) ? $_POST['ji_price'] : 0;
        if ($ji_price) {
            M("user")->where("id=" . $uid)->setDec("jifen", $ji_price * 100);
        }
        if ($ji_price >= $_POST['price']) {
            $price = "0.01";
            $type = "jifen";
        } else {
            $price = $_POST['price'] - $ji_price;
            $type = "weixin";
        }
        //下单
        try {
            $data = array();
            $data['shop_id'] = intval($_POST['brand_id']);
            $data['vid'] = intval($_POST['brand_image_id']);
            $data['uid'] = intval($uid);
            $data['addtime'] = time();
            $data['del'] = 0;
            $data['type'] = $type;
            //订单状态 '0'=>'已取消','10'=>'待付款','20'=>'已付款','30'=>'待发货','40'=>'已发货','50'=>'交易完成','51'=>'交易关闭'
            $data['status'] = 10;//未付款
            $data['post'] = 0;
            $data['price'] = $_POST['price'];
            $data['amount'] = $price;
            $data['price_h'] = $ji_price;
            $data['product_num'] = intval($_POST['num']);//总数量
            $data['order_sn'] = $order_sn . $this->get_last_order_id();//生成唯一订单号

            /*if (!$data['product_num'] || !$data['price']) {
                throw new \Exception("System Error !");
            }*/

            $result = $order->add($data);
            if ($result) {

                $pids_arr = $_POST['pids'];//商品id
                $pids = explode(",", $pids_arr);
                foreach ($pids as $value) {
                    $pid = explode("_", $value);
                    $date = array();
                    $date['order_id'] = $result;//订单id
                    $date['pid'] = $pid[0];//订单id
                    $date['name'] = $product->where('id=' . intval($pid[0]))->getField('name');//商品名字
                    $date['price'] = $product->where('id=' . intval($pid[0]))->getField('price');
                    $date['pro_buff'] = $_POST['buff'];
                    $date['photo_x'] = $product->where('id=' . intval($pid[0]))->getField('photo_x');
                    $date['pro_buff'] = "1";
                    $date['addtime'] = time();
                    $date['num'] = intval($pid[1]);
                    $res = $order_pro->add($date);
                    if (!$res) {
                        throw new \Exception("下单 失败！" . __LINE__);
                    }

                    //检查产品是否存在，并修改库存
                    $check_pro = $product->where('id=' . intval($pid[0]) . ' AND del=0 AND is_down=0')->field('num,shiyong')->find();
                    if (!$check_pro) {
                        throw new \Exception("商品不存在或已下架！");
                    }
                    $up = array();
                    $up['num'] = intval($check_pro['num']) - intval($date['num']);
                    $up['shiyong'] = intval($check_pro['shiyong']) + intval($date['num']);
                    $product->where('id=' . intval($date['pid']))->save($up);
                }
            } else {
                throw new \Exception("下单 失败！");
            }
        } catch (Exception $e) {
            echo json_encode(array('status' => 0, 'err' => $e->getMessage()));
            exit();
        }
        //把需要的数据返回
        $arr = array();
        $arr['order_id'] = $result;
        $arr['order_sn'] = $order_sn;
        //$arr['pay_type'] = $_POST['paytype'];
        $this->json_result($arr);
        exit();
    }

    /**
     * 购物车结算
     * @author tiedong
     * @date 2018-01-19
     */
    public function buy_cart()
    {
        $uid = intval($this->get("id"));
        if (!$uid) {
            echo json_encode(array('status' => 0, 'err' => '登录状态异常.'));
            exit();
        }
        $product = M("product");
        $shopping = M('shopping_char');
        $brand_image = M('brand_image');
        $brand = M('brand');
        $cart_id = trim($_GET['cart_id'], ',');
        $id = explode(',', $cart_id);
        if (!$cart_id) {
            echo json_encode(array('status' => 0, 'err' => '网络异常.' . __LINE__));
            exit();
        }
        $pro = array();
        $canJifen = 0;
        foreach ($id as $k => $v) {
            //检测购物车是否有对应数据
            $check_cart = $shopping->where('id=' . intval($v))->find();
            if (!$check_cart) {
                echo json_encode(array('status' => 0, 'err' => '非法操作.' . __LINE__));
                exit();
            }
            $pids_arr = $check_cart['pids'];
            $pro[$k]['id'] = $check_cart['id'];
            $brandInfo = $brand->where('id=' . $check_cart['shop_id'])->find();
            if ($brandInfo['type']) {
                $canJifen = 1;
            }
            $pro[$k]['name'] = $brandInfo['name'];
            $pro[$k]['brand_photo'] = __DATAURL__ . "UploadFiles/" . $brand_image->where('id=' . $check_cart['gid'])->getField("brand_photo");
            $pro[$k]['price'] = $check_cart['price'];
            $pro[$k]['num'] = $check_cart['num'];
            //查看商品
            $pids = explode(",", $pids_arr);
            $proArr = array();
            foreach ($pids as $value) {
                $pid = explode("_", $value);
                //检查商品是否已经下架或者不存在！
                $check = $this->check_cart(intval($pid[0]));
                if ($check['status'] == 0) {
                    $this->json_error($check['err']);
                    exit;
                }
                //检查商品的库存
                $check = $this->check_num(intval($pid[0]), intval($pid[1]));
                if ($check['status'] == 0) {
                    $this->json_error($check['err']);
                    exit;
                }
                $pro_info = $product->where('id=' . intval($pid[0]))->field('name,price')->find();
                $pro_info['num'] = $pid[1];
                array_push($proArr, $pro_info);
            }
            $pro[$k]['product'] = $proArr;
        }

        //用户积分
        $jifen = M("user")->where('id=' . $uid)->getField("jifen");
        $returnArr = array(
            'jifen'     => $jifen,
            'jf_price'  => $jifen / 100,
            'can_jifen' => $canJifen,
            'product'   => $pro
        );
        $this->json_result($returnArr);
        exit();
    }

    /**
     * 购物车下单结算
     * @author tiedong
     * @date 2018-01-20
     * @throws \Exception
     */
    public function payment()
    {
        $product = M("product");
        $order = M("order");
        $order_pro = M("order_product");
        $shopping = M('shopping_char');
        $uid = intval($this->get("id"));
        if (!$uid) {
            echo json_encode(array('status' => 0, 'err' => '登录状态异常.'));
            exit();
        }
        $cart_id = trim($_POST['cart_id'], ',');
        if (!$cart_id) {
            echo json_encode(array('status' => 0, 'err' => '数据异常.'));
            exit();
        }
        //返回公共的订单号
        $order_sn = $this->build_order_no();
        //获取积分金额
        $ji_price = !empty($_POST['ji_price']) ? $_POST['ji_price'] : 0;
        $num = M('shopping_char')->where("id IN($cart_id)")->field('SUM(num) as num')->find();
        //生成订单
        try {
            $cart_id = explode(',', $cart_id);
            if (empty($ji_price)) {
                $j_price1 = 0;
            } else {
                $count = count($cart_id);
                $j_price1 = number_format($ji_price / $count, 2);
            }
            $order_id_arr = array();
            foreach ($cart_id as $ke => $vl) {
                $shopping_char = $shopping->where('id=' . $vl)->find();
                if ($ji_price >= $shopping_char['price']) {
                    $price = "0.01";
                    $type = "jifen";
                } else {
                    $price = $shopping_char['price'] - $j_price1;
                    $type = "weixin";
                }
                $data['shop_id'] = $shopping_char['shop_id'];
                $data['uid'] = intval($uid);
                $data['vid'] = $shopping_char['gid'];
                $data['price'] = $shopping_char['price'];
                $data['amount'] = $price;
                $data['price_h'] = $ji_price;
                $data['addtime'] = time();
                $data['del'] = 0;
                $data['type'] = $type;
                $data['status'] = 10;
                $data['product_num'] = $shopping_char['num'];
                $data['order_sn'] = $order_sn . $this->get_last_order_id();//生成唯一订单号
                $result = $order->add($data);
                if ($result) {
                    $pids_arr = $shopping_char['pids'];
                    $pids = explode(",", $pids_arr);
                    foreach ($pids as $var) {
                        $pid = explode("_", $var);
                        $date = array();
                        $date['pid'] = $pid[0];
                        $date['name'] = $product->where('id=' . $pid[0])->getField("name");
                        $date['order_id'] = $result;
                        $date['price'] = $product->where('id=' . $pid[0])->getField("price");
                        $date['photo_x'] = $product->where('id=' . $pid[0])->getField("photo_x");
                        $date['addtime'] = time();
                        $date['num'] = $pid[1];
                        $date['pro_guige'] = '';
                        $res = $order_pro->add($date);
                        if (!$res) {
                            throw new \Exception("下单 失败！" . __LINE__);
                        }
                        //检查产品是否存在，并修改库存
                        $check_pro = $product->where('id=' . intval($date['pid']) . ' AND del=0 AND is_down=0')
                            ->field('num,shiyong')
                            ->find();
                        $up = array();
                        $up['num'] = intval($check_pro['num']) - intval($date['num']);
                        $up['shiyong'] = intval($check_pro['shiyong']) + intval($date['num']);
                        $product->where('id=' . intval($date['pid']))->save($up);
                    }
                    $order_id_arr[] = $result;

                    //删除购物车数据
                    $shopping->where('uid=' . intval($uid) . ' AND id=' . intval($vl))->delete();
                } else {
                    throw new \Exception("下单 失败！");
                }
            }
            $order_ids = implode('|', $order_id_arr);
        } catch (Exception $e) {
            echo json_encode(array('status' => 0, 'err' => $e->getMessage()));
            exit();
        }
        $arr = array();
        $arr['order_id'] = $order_ids;
        $arr['order_sn'] = $order_sn;
        $this->json_result($arr);
        exit();
    }

    //****************************
    // 获取可用优惠券
    //****************************
    public function get_voucher($uid, $pid, $cart_id)
    {
        $qz = C('DB_PREFIX');
        //计算总价
        $prices = 0;
        foreach ($cart_id as $ks => $vs) {
            $pros = M('shopping_char')->where('' . $qz . 'shopping_char.uid=' . intval($uid) . ' AND ' . $qz . 'shopping_char.id=' . $vs)->join('LEFT JOIN __PRODUCT__ ON __PRODUCT__.id=__SHOPPING_CHAR__.pid')->join('LEFT JOIN __SHANGCHANG__ ON __SHANGCHANG__.id=__SHOPPING_CHAR__.shop_id')->field('' . $qz . 'shopping_char.num,' . $qz . 'shopping_char.price,' . $qz . 'shopping_char.type')->find();
            $zprice = $pros['price'] * $pros['num'];
            $prices += $zprice;
        }
        $condition = array();
        $condition['uid'] = intval($uid);
        $condition['status'] = array('eq', 1);
        $condition['start_time'] = array('lt', time());
        $condition['end_time'] = array('gt', time());
        $condition['full_money'] = array('elt', floatval($prices));

        $vou = M('user_voucher')->where($condition)->order('addtime desc')->select();
        $vouarr = array();
        foreach ($vou as $k => $v) {
            $chk_order = M('order')->where('uid=' . intval($uid) . ' AND vid=' . intval($v['vid']) . ' AND status>0')->find();
            $vou_info = M('voucher')->where('id=' . intval($v['vid']))->find();
            $proid = explode(',', trim($vou_info['proid'], ','));
            if (($vou_info['proid'] == 'all' || $vou_info['proid'] == '' || in_array($pid, $proid)) && !$chk_order) {
                $arr = array();
                $arr['vid'] = intval($v['vid']);
                $arr['full_money'] = floatval($v['full_money']);
                $arr['amount'] = floatval($v['amount']);
                $vouarr[] = $arr;
            }
        }

        return $vouarr;
    }

    public function ceshi()
    {
        print_r("adads");
        die();
    }

    /**针对涂屠生成唯一订单号
     * @return int 返回16位的唯一订单号
     */
    public function build_order_no()
    {
        return date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
    }

    /**
     * 获取最后一个订单id
     *
     * @author    Doujia
     * @return    string
     */
    public function get_last_order_id()
    {
        //获取最后一个订单
        $order_model = M("order");
        $id = $order_model->order('id desc')->limit(0, 1)->getField("id") + 1;
        return $id;
    }
}